<template>
	<view class="buy-panel">
		<uni-popup ref="buypopup" type="center" @change="change">
			<view class="buy-content">
				<view class="content">
					<product-selected-sku-com></product-selected-sku-com>
					<product-attribute-selector-com v-if="hasAttribute"></product-attribute-selector-com>
					<product-sku-selector-com v-else></product-sku-selector-com>
					<!-- <view class="line" v-if="is_gold_bean"></view> -->
					<product-selected-sku-count-com ></product-selected-sku-count-com>
					<view class="submit">
						<view class= "money">￥{{ sku.price_vip*selectedSkuCount }}</view>
						<button class="button" plain="true" @click="submitOrder">立即购买</button>
					</view>
				</view>
			</view>
		</uni-popup>
		
		<uni-popup ref="shoppingpopup" type="center" @change="change">
			<view class="buy-content">
				<view class="content">
					<product-selected-sku-com></product-selected-sku-com>
					<product-attribute-selector-com v-if="hasAttribute"></product-attribute-selector-com>
					<product-sku-selector-com v-else></product-sku-selector-com>
					<!-- <view class="line" v-if="is_gold_bean"></view> -->
					<product-selected-sku-count-com ></product-selected-sku-count-com>
					<view class="submit">
						<view class= "money">￥{{ sku.price_vip*selectedSkuCount }}</view>
						<button class="button" plain="true" @click="submitShoppingCart">加入购物车</button>
					</view>
				</view>
			</view>
		</uni-popup>
		<uni-popup ref="takepopup" type="center" @change="change">
			<view class="buy-content">
				<view class="content">
					<product-selected-sku-com></product-selected-sku-com>
					<view class="drink-attr">
						<view v-for="(drinkAttr, index) in drinkAttrs" :key="index">
							<view class="drink-attr-name">{{drinkAttr.name}}</view>
							<view class="attr-block">
								 <block  v-for="(attr, aindex) in drinkAttr.attrs" :key="aindex">
									<view class="attr-name-select" v-if="attr.selected==true" @click="selectValue(drinkAttr.id, attr.id)">{{attr.name}} ￥{{ attr.price }}</view>
									<view class="attr-name" v-else @click="selectValue(drinkAttr.id, attr.id ,true)">{{attr.name}} ￥{{ attr.price }}</view>
								 </block>
							</view>
						</view>
					</view>
					<view class="submit">
						<view class= "money">￥{{ drinkPrice }}</view>
						<button class="button" plain="true" @click="submitTakeWine">立即提货</button>
					</view>
				</view>
			</view>
		</uni-popup>
		<shopping-cart-com :product="product"></shopping-cart-com>
		<view class="buy" v-if="isTake">
			<view class="take-button" @click="openTakePanel">提货</view>
		</view>
		<view class="buy" v-else> 
			<view class="service" open-type="contact" :plain="true" @click="customerService">
				<image class="earphone" mode="aspectFit" src="/static/images/service.png"></image>
				<view class="text">客服</view>
			</view>
			<view class="service" @click="shareProduct">
				<image class="earphone" src="/static/images/sharebtn.png" mode=""></image>
				<view class="text">分享</view>
			</view>
			
			<view class="shopping" @click="openShoppingPanel">
				<view class="shopping-button" plain="true">加入购物车</view>
			</view>
			<view class="button" @click="openBuyPanel">
				<view class="buy-button" plain="true">立即购买</view>
			</view>
		</view>
		<view class="msg-pop">
			<uni-popup ref="msgpopup" type="center">
				<view class="popbgmsg-box" @click="close()">
					<image src="/static/images/common/popbgmsg.png" class="popbgmsg" mode=""></image>
					<view class="pop-content">2022年1月28日至2月15日春节放假、快递停发，平台暂不支持购买商品和购买会员。</view>
				</view>
			</uni-popup>
		</view>
	</view>
</template>

<script>
	import store from 'store'
	import CurrentUser from "mixins/CurrentUser"
	import CommonMethods from "mixins/CommonMethods"
	import { mapGetters,mapActions } from 'vuex'
	import ProductSelectedSkuCom from "./ProductSelectedSkuCom"
	import ProductAttributeSelectorCom from "./ProductAttributeSelectorCom"
	import ProductSelectedSkuCountCom from "./ProductSelectedSkuCountCom"
	import ProductSkuSelectorCom from "./ProductSkuSelectorCom"
	import ShoppingCartCom from "../ShoppingCartCom"
	import { getCarts,createCart } from 'api/cartApi.js';
	import { getDrinkCategory } from 'api/drinkApi.js';  
	
	export default {
		name: "ProductBuyPanelCom",
		store,
		mixins: [CurrentUser, CommonMethods],
		components: {
			ProductSelectedSkuCom,
			ProductSkuSelectorCom,
			ProductAttributeSelectorCom,
			ProductSelectedSkuCountCom,
			ShoppingCartCom
		},
		props:{
			productId: {
			  default:''
			},
			is_gold_bean:{
				default:false
			},
			source:{
				default:'wap'
			},
			isTake:{
				default:false
			}
			
		},
		computed: {
			...mapGetters([
				'user',
				'isLogin',
				'hasAttribute',
				'selectedSku',
				'defaultSku',
				'selectedSkuCount',
				'product',
				'shoppingCartNum'
			])
		},
		data(){
			return {
				iscurrent:true,
				sku:{},
				drinkAttrs:[],
				drinkPrice:0,
				attrIds:[],
			}
		},
		mounted() {
			
		},
		watch: {
		  defaultSku: {
		    handler(val) {
		      if (!this.selectedSku) {
		         this.sku=  val
		      }
		    },
		    immediate: true
		  },
		  selectedSku: {
		    handler(val) {
		      if (val) {
		        this.sku=  val
				
		      }
		    },
		    immediate: true
		  }
		},
		methods: {
			...mapActions(['refreshSelectedSkuCount','refreshShoppingCartNum','getUserCartsCount']),
			showmsg() {
				this.$refs.msgpopup.open('center')
			},
			close() {
				this.$refs.msgpopup.close()
			},
			shareProduct() {
				this.$emit('shareProduct')
			},
			async	change(e){
				if(!e.show){
					if(this.iscurrent){
						await this.refreshSelectedSkuCount(1)
					}
				}
			},
			async selectValue(keyId, valueId, isSelected = false) {
				
				this.drinkAttrs.forEach((item, index) => {
					if(item.attrs){
						item.attrs.forEach((attr, aindex) => {
							if(isSelected === true && item.id ==keyId){
								
								if(attr.id != valueId && attr.selected ==true){
									
									this.drinkPrice = parseInt(this.drinkPrice) - parseInt(attr.price);
									delete this.attrIds[attr.id];
								}
								attr.selected = false;
							} 
							if(attr.id == valueId){
								if(isSelected === true){
									attr.selected = true;
									this.drinkPrice = parseInt(this.drinkPrice) + parseInt(attr.price);
									//if(!this.attrIds[attr.id]){
										this.attrIds[attr.id] = attr.id;
									//}
									
								}else{
									attr.selected = false;
									this.drinkPrice = parseInt(this.drinkPrice) - parseInt(attr.price);
									delete this.attrIds[attr.id];
								}
								
							}
							
						})
						
					}
					
				})
				this.$forceUpdate();
				
			},
			deleteAttrId(){
				
				
			},
			async openBuyPanel() {
				if(this.source == 'wap'){
					if (await this.isLogin) {
						// uni.navigateTo({url: '/packs/pages/download/download'})
						
						// 创建订单底部弹框
						this.$refs.buypopup.open('center')
						
					} else {
						uni.getStorage({
							key: 'invite_code',
							success: function (res) {
								let invite_code = res.data
								uni.navigateTo({
									url: `/packs/pages/auth/auth?invite_code=${invite_code}&product_id=${this.productId}`
								})
							},
							fail() {
								uni.navigateTo({
									url: '/packs/pages/auth/auth?from=product'
								})
							}
						})
					}
				}else{
					this.$refs.buypopup.open('center')
				}
			},
			async openShoppingPanel() {
				if(this.source == 'wap'){
					if (await this.isLogin) {
						// 创建订单底部弹框
						this.$refs.shoppingpopup.open('center')
						
					} else {
						uni.getStorage({
							key: 'invite_code',
							success: function (res) {
								let invite_code = res.data
								uni.navigateTo({
									url: `/packs/pages/auth/auth?invite_code=${invite_code}&product_id=${this.productId}`
								})
							},
							fail() {
								uni.navigateTo({
									url: '/packs/pages/auth/auth?from=product'
								})
							}
						})
					}
				}else{
					this.$refs.shoppingpopup.open('center')
				}
			},
			async openTakePanel() {
				if(this.source == 'wap'){
					if (await this.isLogin) {
						this.$refs.takepopup.open('center')
						
					} else {
						uni.getStorage({
							key: 'invite_code',
							success: function (res) {
								let invite_code = res.data
								uni.navigateTo({
									url: `/packs/pages/auth/auth?invite_code=${invite_code}&product_id=${this.productId}`
								})
							},
							fail() {
								uni.navigateTo({
									url: '/packs/pages/auth/auth?from=product'
								})
							}
						})
					}
				}else{
					this.$refs.takepopup.open('center')
				}
			},
			customerService(){
				location.href = 'weixin://dl/business/?t=svbvUImDUma'
			},
			async submitOrder() {
				this.iscurrent = false
				if(this.source == 'wap'){
					if (await this.isLogin) {
						if (this.selectedSku) {
							let records = [];
							
							let params = {
								product:this.product,
								sku:this.sku,
								number: this.selectedSkuCount,
							}
							records.push(params);	
							uni.navigateTo({
								url:'/packs/pages/order/confirm?records=' + encodeURIComponent(JSON.stringify(records))
							})
							this.$refs.buypopup.close()
							this.iscurrent = true 
						} else {
							uni.showToast({
								title: '请选择规格',
								mask: true,
								icon: 'none',
								position: 'bottom',
								duration: 2000
							});
						}
					} else {
						uni.redirectTo({
							url: '/packs/pages/auth/auth'
						})
					}
				}else{
					if (this.selectedSku) {
						uni.navigateTo({
							url: `/packs/pages/order/confirm`
						})
						this.$refs.buypopup.close()
						this.iscurrent = true 
					} else {
						uni.showToast({
							title: '请选择规格',
							mask: true,
							icon: 'none',
							position: 'bottom',
							duration: 2000
						});
					}
				}
			},
			async submitShoppingCart() {
				this.iscurrent = false
				if(this.source == 'wap'){
					if (await this.isLogin) {
						if (this.selectedSku) {
							
							let params = {
								product_id:this.productId,
								sku_id:this.sku.id,
								number: this.selectedSkuCount,
							}
							
							createCart(params).then(res=>{
								if(!res.message){
									let cartNum = parseInt(this.shoppingCartNum) + this.selectedSkuCount ;
									console.log(cartNum);
									this.refreshShoppingCartNum(cartNum);
									/* this.shoppingCartNum = this.shoppingCartNum + this.selectedSkuCount ;
									console.log(this.shoppingCartNum); */
								}else{
									uni.showModal({
									  title: '提示', content: Object.values(res.errors)[0][0], showCancel: false
									})
								}
								
							})
							this.$refs.shoppingpopup.close()
							this.iscurrent = true 
						} else {
							uni.showToast({
								title: '请选择规格',
								mask: true,
								icon: 'none',
								position: 'bottom',
								duration: 2000
							});
						}
					} else {
						uni.redirectTo({
							url: '/packs/pages/auth/auth'
						})
					}
				}else{
					if (this.selectedSku) {
						uni.navigateTo({
							url: `/packs/pages/order/confirm`
						})
						this.$refs.shoppingpopup.close()
						this.iscurrent = true 
					} else {
						uni.showToast({
							title: '请选择规格',
							mask: true,
							icon: 'none',
							position: 'bottom',
							duration: 2000
						});
					}
				}
			},
			async submitTakeWine() {
				let ids = this.attrIds.filter(function (s) {
					return s; 
				})
				if(ids.length < this.drinkAttrs.length){
					uni.showToast({
						title: '请选择规格',
						mask: true,
						icon: 'none',
						position: 'bottom',
						duration: 2000
					});
					return ;
				}
				let attr = ids.join('-');
					if(this.source == 'wap'){
						if (await this.isLogin) {
							if (attr) {
								
								let records = [];
								
								let params = {
									product:this.product,
									sku:this.sku,
									number: this.selectedSkuCount,
									attr:attr,
									price:this.drinkPrice,
								}
								records.push(params);	
								uni.navigateTo({
									url:'/packs/pages/order/confirm?records=' + encodeURIComponent(JSON.stringify(records))
								})
								this.$refs.takepopup.close()
								this.iscurrent = true 
							} else {
								uni.showToast({
									title: '请选择规格',
									mask: true,
									icon: 'none',
									position: 'bottom',
									duration: 2000
								});
							}
						} else {
							uni.redirectTo({
								url: '/packs/pages/auth/auth'
							})
						}
					}else{
						if (this.attr) {
							uni.navigateTo({
								url: `/packs/pages/order/confirm`
							})
							this.$refs.takepopup.close()
							this.iscurrent = true 
						} else {
							uni.showToast({
								title: '请选择规格',
								mask: true,
								icon: 'none',
								position: 'bottom',
								duration: 2000
							});
						}
					}
				}
			
		},
		
		async created() {
			const response = await getDrinkCategory();
			if(response){
				this.drinkAttrs = response;
			}
		}
	}
</script>

<style lang="scss" scoped>
	.buy-panel {
		width: 100%;
		position: fixed;
		bottom: 0;
		z-index: 999;
		background-color: white;

		.buy-content {
			
			background: white;
			z-index: 999;
			width:636rpx;
			border-radius:10rpx;
			.content {
				width: 100%;
				margin: 38rpx auto;
				.line{
					width: 100%;
					height: 2rpx;
					background: #EEEEEE;
					margin-top: 20rpx;
				}
				.submit {
					margin-top:30rpx;
					padding-bottom:30rpx;
					overflow: hidden;
					.money{
						color:#333;
						font-size:32rpx;
						float:left;
						margin-left:20rpx;
					}
					.button {
						width: 218rpx;
						height: 76rpx;
						line-height: 76rpx;
						background: #D84C29; 
						border: none;
						border-radius: 10rpx;
						font-size: 32rpx;
						color: #fff;
						float:right;
						margin-right:20rpx;
					}
				}
			}
		}
		
		.buy {
			display: flex;
			justify-content: center;
			border-top: 1px #EEEEEE solid;
			padding: 40rpx;

			.service {
				height: 64rpx;
				padding: 0;
				line-height: 24rpx;
				margin-top: 5rpx;
				margin-right: 30rpx;
				border: none;

				.earphone {
					width: 40rpx;
					height: 40rpx;
				}

				.text {
					font-size: 24rpx;
					color: #555555;
					margin-top:10rpx; 
				}
			}

			.button {
				.buy-button {
					width: 228rpx;
					height: 68rpx;
					line-height: 68rpx;
					background: #D84C29;
					font-size: 30rpx;
					color: #fff;
					text-align: center;
					border:1rpx solid #D84C29;
				}
			}
			.take-button {
				width: 552rpx;
				height: 68rpx;
				line-height: 68rpx;
				background: #D84C29;
				font-size: 30rpx;
				color: #fff;
				text-align: center;
				border:1rpx solid #D84C29;
			}
		}
	}
	.shopping{
		
		width:208rpx;
		height:68rpx;
		border:1rpx solid #999;
		color:#333;
		font-size:30rpx;
		line-height:68rpx;
		text-align: center;
		margin-left:36rpx;
		margin-right:36rpx;
	}
	.share-btn{
		display: flex;
		align-items: flex-end;
		margin-right: 20rpx;
		// margin-left: 242rpx;
		>image{
			display: block;
			width:36rpx;
			height: 36rpx;
		}
		>view{
			font-size: 24rpx;
			font-family: PingFangSC-Regular, PingFang SC;
			font-weight: 400;
			color: #333;
			
		}
	}
	.popbgmsg-box {
		width: 560rpx;
		height: 980rpx;
		margin-top: 50rpx;
		position: relative;

	}

	.popbgmsg {
		display: block;
		width: 560rpx;
		height: 980rpx;
	}

	.pop-content {
		width: 354rpx;
		max-height: 260rpx;
		text-overflow: -o-ellipsis-lastline;
		overflow: hidden;
		text-overflow: ellipsis;
		display: -webkit-box;
		-webkit-line-clamp: 6;
		line-clamp: 6;
		-webkit-box-orient: vertical;
		position: absolute;
		left: 104rpx;
		top: 344rpx;
		top:400rpx;
		font-size: 28rpx;
		font-family: PingFangSC-Regular, PingFang SC;
		font-weight: 400;
		color: #A73501;
		line-height: 40rpx;
	}
	.drink-attr{
		margin-left:20rpx;
		.drink-attr-name{
			margin-top:40rpx;
			font-size:28rpx;
			color:#333;
		}
		.attr-block{
			display:flex;
			margin-top:16rpx;
			.attr-name{
				height:58rpx;
				line-height:58rpx;
				background:#f2f2f2;
				border-radius: 10rpx;
				font-size:28rpx;
				color:#333;
				padding:0rpx 16rpx;
				border:2rpx solid #f2f2f2;
			}
			.attr-name-select{
				height:58rpx;
				line-height:58rpx;
				background:#fff;
				font-size:28rpx;
				color:#D84C29;
				padding:0rpx 16rpx;
				border:2rpx solid #D84C29;
				border-radius: 10rpx;
				
				
			}
			.attr-name:not(:first-child){
				margin-left:32rpx;
			}
			.attr-name-select:not(:first-child){
				margin-left:32rpx;
			}
		}
	}
</style>
